﻿<#
.SYNOPSIS
  Deploys a Service Gateway Management Console.
.DESCRIPTION
  Creates the Azure Website and associated Azure SQL Database to host a Service Gateway Management Console website and deploys the latest version of
  the console software to that site. 

.EXAMPLE
  .\DeployMooncake.ps1 -Subscription "MySubscriptionName" -Location "China East" -ConsoleName "MyGatewayConsole" `
		-DatabaseUser "DbUserName" -DatabasePassword "DbPassword" `
		-ApplicationId "AAD Application Client Id GUID" -ApplicationKey "AAD Application Key" `
		-Environment "AzureCloud|AzureChinaCloud"

#>

param (
    # Subscription name to create Console + DB in
    [Parameter(Mandatory = $true)]
    [String]$Subscription,
    
    # Location
    [Parameter(Mandatory = $true)]
    [String]$Location,
    
    # Name of Console Website
    [Parameter(Mandatory = $true)]
    [String]$ConsoleName,
    
    # Database Username
    [Parameter(Mandatory = $true)]
    [String]$DatabaseUser,
    
    # Database Password
    [Parameter(Mandatory = $true)]
    [String]$DatabasePassword,
    
    # Application ID
    [Parameter(Mandatory = $true)]
    [String]$ApplicationId,
    
    # Application Key
    [Parameter(Mandatory = $true)]
    [String]$ApplicationKey,
    
    # Environment
    [Parameter(Mandatory = $true)]
    [String]$Environment
    )


# Check if Windows Azure Powershell is avaiable
if ((Get-Module -ListAvailable Azure) -eq $null)
{
    throw "Windows Azure Powershell not found! Please make sure to install them from http://www.windowsazure.com/en-us/downloads/#cmd-line-tools"
}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Deployment")

Add-AzureAccount -Environment $Environment

Select-AzureSubscription -SubscriptionName $Subscription
$azureSubscription = Get-AzureSubscription -Current

$consoleWebsite = New-AzureWebsite -Location $Location -Name $ConsoleName

$consoleDbServer = New-AzureSqlDatabaseServer -Location $Location -AdministratorLogin $DatabaseUser -AdministratorLoginPassword $DatabasePassword
$azureAccessRule = New-AzureSqlDatabaseServerFirewallRule -ServerName $consoleDbServer.ServerName -RuleName ([Guid]::NewGuid()).ToString() -StartIpAddress 0.0.0.0 -EndIpAddress 0.0.0.0

$consoleDb = New-AzureSqlDatabase -ServerName $consoleDbServer.ServerName -DatabaseName $ConsoleName
$connectString = 'Server=tcp:' + $consoleDbServer.ServerName + $azureSubscription.SqlDatabaseDnsSuffix + ',1433;Database=' + $consoleDb.Name + ';User ID=' + $DatabaseUser + '@' + $consoleDbServer.ServerName + ';Password=' + $DatabasePassword + ';Trusted_Connection=False;Encrypt=True;Connection Timeout=30;'

$webclient = New-Object System.Net.WebClient
$localPackage = $env:TEMP + '\console.zip'
$localParameters = $env:TEMP + '\console.setparameters.xml'

$webclient.DownloadFile('https://www.service-gateway.net/managementconsole/latest/console/console.zip', $localPackage)
$webclient.DownloadFile('https://www.service-gateway.net/managementconsole/latest/console/console.setparameters.xml', $localParameters)

$consoleProperties = $consoleWebsite.SiteProperties.Properties
$publishUrl = ($consoleProperties | where { $_.Name -eq "RepositoryURI" }).Value + "/MsDeploy.axd?site=" + $consoleWebsite.Name

$deploymentSource = [Microsoft.Web.Deployment.DeploymentManager]::CreateObject('package', $localPackage)

$destBaseOptions = new-object Microsoft.Web.Deployment.DeploymentBaseOptions
$destBaseOptions.ComputerName = $publishUrl
$destBaseOptions.UserName = $consoleWebsite.PublishingUsername
$destBaseOptions.Password = $consoleWebsite.PublishingPassword
$destBaseOptions.AuthenticationType = 'Basic'

$deploymentSource.SyncParameters.Load($localParameters)
$deploymentSource.SyncParameters['AD_RealmAppSetting'].Value = '1'
$deploymentSource.SyncParameters['AD_AudienceUriAppSetting'].Value = '1'
$deploymentSource.SyncParameters['AD_ClientID'].Value = $ApplicationId
$deploymentSource.SyncParameters['AD_ClientPassword'].Value = $ApplicationKey
$deploymentSource.SyncParameters['AD_APPIDUri'].Value = 'http://' + $consoleWebsite.HostNames[0] + '/'
$deploymentSource.SyncParameters['ConsoleContext-Web.config Connection String'].Value = $connectString
$deploymentSource.SyncParameters['AD_Tenant'].Value = $azureSubscription.ActiveDirectoryTenantId
$deploymentSource.SyncParameters['ApplicationInitialized'].Value = 'true'
$deploymentSource.SyncParameters['AzureEnvironment'].Value = $Environment
$deploymentSource.SyncParameters['AD_Issuer'].Value = $azureSubscription.ActiveDirectoryEndpoint + 'common/wsfed'
$deploymentSource.SyncParameters['AD_MetadataUrl'].Value = $azureSubscription.ActiveDirectoryEndpoint + 'common/FederationMetadata/2007-06/FederationMetadata.xml'

$syncOptions = new-object Microsoft.Web.Deployment.DeploymentSyncOptions
$deploymentSource.SyncTo('contentPath', $consoleWebsite.Name, $destBaseOptions, $syncOptions)

